Python实现统计文本当中单词的数量,

您所在的位置:网站首页 python nltk怎么统计单词出现频率 Python实现统计文本当中单词的数量,

Python实现统计文本当中单词的数量,

#Python实现统计文本当中单词的数量,| 来源: 网络整理| 查看: 265

  这是阿里巴巴2016年的一道面试题:

统计英文文章中单词出现的次数,并且输出出现次数的前10个单词

文本如下:

Accessing Text from the Web and from Disk Electronic Books A small sample of texts from Project Gutenberg appears in the NLTK corpus collection. However, you may be interested in analyzing other texts from Project Gutenberg. You can browse the catalog of 25,000 free online books at http://www.gutenberg.org/catalog/, and obtain a URL to an ASCII text file. Although 90% of the texts in Project Gutenberg are in English, it includes material in over 50 other languages, including Catalan, Chinese, Dutch, Finnish, French, German, Italian,

先简单的看了下文章,基本单词间的分隔都是空格,或者是逗号加空格

方法一

1、先打开文档,进行初步分析

def read_file(): f=open('F:\\Python\\testfile\\test_3.txt') readline=f.readlines() word=[]#存储单词 #得到文章的单词并且存入列表中: for line in readline: #因为原文中每个单词都是用空格 或者逗号加空格分开的, line=line.replace(',','')#除去逗号只要空格来分开单词 line=line.strip()#除去左右的空格 wo=line.split(' ') word.extend(wo) return word

2、简单的清理和排序

def clear_account(lists): #去除重复的值 wokey={} wokey=wokey.fromkeys(lists)#此代码的意思为将lists的元素作为wokey的键值key#通过这个代码可以除去重复的列表元素 word_1=list(wokey.keys()) #然后统计单词出现的次数,并将它存入一个字典中 for i in word_1: wokey[i]=lists.count(i) return wokey 3、对单词进行排序(因为我们存入的是一个字典,所以其实是对字典排序)

def sort_1(wokey): #删除''字符 del[wokey['']]#因为我发现字典中存在空元素,所以删去 #排序,按values进行排序,如果是按key进行排序用sorted(wokey.items(),key=lambda d:d[0],reverse=True) wokey_1={} wokey_1=sorted(wokey.items(),key=lambda d:d[1],reverse=True) #得到的是一个列表,里面的元素为元组,所以再把他转化为字典,不过不转化也可以 wokey_1=dict(wokey_1) return wokey_1 4、输出结果

def main(wokey_1): #输出前10个 i=0 for x,y in wokey_1.items(): if i


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3